<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class AdminMenuSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->command->info('🔧 开始配置后台菜单...');

        // 检查是否已存在"书籍管理"菜单
        $existingMenu = DB::table('admin_menu')->where('title', '书籍管理')->first();

        if ($existingMenu) {
            $this->command->info('ℹ️ "书籍管理"菜单已存在，跳过创建');
            $parentMenuId = $existingMenu->id;
        } else {
            // 创建父级菜单
            $parentMenuId = DB::table('admin_menu')->insertGetId([
                'parent_id' => 0,
                'order' => $this->getNextOrder(0),
                'title' => '书籍管理',
                'icon' => 'fa-book',
                'uri' => '',
                'extension' => '',
                'show' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            $this->command->info('✅ 创建父级菜单: 书籍管理');
        }

        // 检查是否已存在"书籍列表"子菜单
        $existingSubMenu = DB::table('admin_menu')
            ->where('title', '书籍列表')
            ->where('parent_id', $parentMenuId)
            ->first();

        if ($existingSubMenu) {
            $this->command->info('ℹ️ "书籍列表"子菜单已存在，跳过创建');
        } else {
            // 创建子菜单
            DB::table('admin_menu')->insert([
                'parent_id' => $parentMenuId,
                'order' => $this->getNextOrder($parentMenuId),
                'title' => '书籍列表',
                'icon' => 'fa-list',
                'uri' => '/category',
                'extension' => '',
                'show' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            $this->command->info('✅ 创建子菜单: 书籍列表');
        }


        $this->command->info('🎉 书籍菜单配置完毕！');
    }


    /**
     * 获取下一个排序号
     */
    protected function getNextOrder($parentId)
    {
        $maxOrder = DB::table('admin_menu')
            ->where('parent_id', $parentId)
            ->max('order');

        return $maxOrder ? $maxOrder + 1 : 1;
    }

    /**
     * 移除菜单（卸载时使用）
     */
    public static function removeMenus()
    {
        // 删除子菜单
        $parentMenu = DB::table('admin_menu')->where('title', '书籍管理')->first();

        if ($parentMenu) {
            // 删除所有子菜单
            DB::table('admin_menu')->where('parent_id', $parentMenu->id)->delete();

            // 删除父菜单
            DB::table('admin_menu')->where('id', $parentMenu->id)->delete();
        }
    }
}
